package com.jiyun.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiyun.dto.EmpDto;
import com.jiyun.entity.Kaoqin;
import com.jiyun.service.IKaoqinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  控制层
 * </p>
 *
 * @author 聪哥哥
 * @since 2023-02-27
 */
@RestController
@RequestMapping("/kaoqin")
public class KaoqinController {

    @Autowired
    IKaoqinService kaoqinService;

    /**
     * 添加接口
     */
    @RequestMapping("/add")
    public void addKaoqin(@RequestBody Kaoqin kaoqin){
        kaoqinService.save(kaoqin);
    }

    /**
     * 修改接口
     */
    @RequestMapping("/update")
    public void updateKaoqin(@RequestBody Kaoqin kaoqin){
        kaoqinService.updateById(kaoqin);
    }

    /**
     * 单个删除接口
     */
    @RequestMapping("/deleteOne")
    public void deleteOne(@RequestParam Integer id){
        kaoqinService.removeById(id);
    }

    /**
     * 批量删除接口
     * 前台ajax参数ids传入示例：1,2,3  (英文逗号分隔的字符串)
     */
    @RequestMapping("/deleteBatch")
    public void deleteBatch(@RequestParam List<Integer> ids){
        kaoqinService.removeByIds(ids);
    }

    /**
     * 根据id查询实体接口
     */
    @RequestMapping("/findById")
    public Kaoqin findById(@RequestParam Integer id){
        return kaoqinService.getById(id);
    }

    /**
     * 查询所有接口
     */
    @RequestMapping("/findAll")
    public List<Kaoqin> findAll(){
        return kaoqinService.list();
    }

    /**
     * 分页查询接口
     * 重要提示：启用分页功能必须在配置类中添加mybatis-plus分页的拦截器
     * 重要提示：启用分页功能必须在配置类中添加mybatis-plus分页的拦截器
     * 重要提示：启用分页功能必须在配置类中添加mybatis-plus分页的拦截器
     */
    @RequestMapping("/findPage")
    public Page<Kaoqin> findPage(@RequestParam Integer page,@RequestParam Integer pageSize){
        Page<Kaoqin> kaoqinPage = new Page<>(page, pageSize);
        return kaoqinService.page(kaoqinPage);
    }

    @PostMapping("findEmpKaoqinDetail")
    public List<Map> findEmpKaoqinDetail(@RequestBody EmpDto empDto) throws Exception{

        /**
         * 1、需要一个日期范围
         * 2、造出这个日期范围内的所有打卡数据，如果数据库有记录，就用数据库的，如果没有那就造一条未打卡记录
         *      2023-02-01 上班卡
         *      2023-02-02 上班卡
         * 3、把所有数据返回前台
         * 已知参数：
         *  查询的月份，格式：2023-02-28 15:00:00
         *  工号：0002
         *  姓名：xxx
         */


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        String queryMonth = simpleDateFormat.format(empDto.getQueryMonth());//格式：2023-02

        LocalDate start = LocalDate.parse(queryMonth + "-01");//2023-02-01
        LocalDate end = start.plusMonths(1).minusDays(1);//2023-02-28


        ArrayList<Map> result = new ArrayList<>();



        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        while (true){
            //查询：从开始日期的上班卡和下班卡数据
            String typeShangban = "上班卡";
            String typeXiaban = "下班卡";

            //上班卡数据
            LambdaQueryWrapper<Kaoqin> kaoqinLambdaQueryWrapper = new LambdaQueryWrapper<>();
            kaoqinLambdaQueryWrapper.eq(Kaoqin::getWorknum,empDto.getWorknum());
            kaoqinLambdaQueryWrapper.eq(Kaoqin::getWorkDate,start);
            kaoqinLambdaQueryWrapper.eq(Kaoqin::getType,typeShangban);
            Kaoqin shangban = kaoqinService.getOne(kaoqinLambdaQueryWrapper);
            if (shangban==null) {
                shangban = new Kaoqin();
                shangban.setName(empDto.getName());
                shangban.setWorknum(empDto.getWorknum());
                shangban.setType(typeShangban);
                shangban.setWorkDate(sdf1.parse(start.toString()));
            }
            shangban.setRule(sdf2.parse(start.toString()+" 08:15:00"));//规定打卡时间处理


            Map shangbanMap = JSONObject.parseObject(JSONObject.toJSONString(shangban), Map.class);
            if (shangban.getDakaTime()==null) {//证明缺卡
                shangbanMap.put("result","未打卡");
            }else{
                if (shangban.getDakaTime().getTime()<=shangban.getRule().getTime()) {
                    shangbanMap.put("result","正常");
                }else{
                    shangbanMap.put("result","迟到");
                }
            }

            result.add(shangbanMap);

            //下班卡数据
            LambdaQueryWrapper<Kaoqin> kaoqinLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            kaoqinLambdaQueryWrapper1.eq(Kaoqin::getWorknum,empDto.getWorknum());
            kaoqinLambdaQueryWrapper1.eq(Kaoqin::getWorkDate,start);
            kaoqinLambdaQueryWrapper1.eq(Kaoqin::getType,typeXiaban);


            Kaoqin xiaban = kaoqinService.getOne(kaoqinLambdaQueryWrapper1);
            if (xiaban==null) {
                xiaban = new Kaoqin();
                xiaban.setName(empDto.getName());
                xiaban.setWorknum(empDto.getWorknum());
                xiaban.setType(typeXiaban);
                xiaban.setWorkDate(sdf1.parse(start.toString()));
            }
            xiaban.setRule(sdf2.parse(start.toString()+" 17:50:00"));//规定打卡时间处理

            Map xiabanMap = JSONObject.parseObject(JSONObject.toJSONString(xiaban), Map.class);
            if (xiaban.getDakaTime()==null) {//证明缺卡
                xiabanMap.put("result","未打卡");
            }else{
                if (xiaban.getDakaTime().getTime()>=xiaban.getRule().getTime()) {
                    xiabanMap.put("result","正常");
                }else{
                    xiabanMap.put("result","早退");
                }
            }

            result.add(xiabanMap);

            start = start.plusDays(1);//天数加1
            if(start.isAfter(end)){
                break;
            }
        }
        return result;
    }

    @RequestMapping("addDaka")
    public void addDaka(@RequestBody Kaoqin kaoqin) throws Exception{


        Date dakaTime = kaoqin.getDakaTime();//2023-02-01 18:00:00

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        kaoqin.setWorkDate(sdf1.parse(sdf1.format(dakaTime)));
        if(kaoqin.getType().equals("上班卡")){
            kaoqin.setRule(sdf2.parse(sdf1.format(dakaTime)+" 08:15:00"));
        }else{
            kaoqin.setRule(sdf2.parse(sdf1.format(dakaTime)+" 17:50:00"));
        }
        //查询数据库中的打卡记录，上班卡保留最早的，下班保留最晚的
        if(kaoqin.getType().equals("上班卡")){
            LambdaQueryWrapper<Kaoqin> kaoqinLambdaQueryWrapper = new LambdaQueryWrapper<>();
            kaoqinLambdaQueryWrapper.eq(Kaoqin::getWorknum,kaoqin.getWorknum());
            kaoqinLambdaQueryWrapper.eq(Kaoqin::getWorkDate,kaoqin.getWorkDate());
            kaoqinLambdaQueryWrapper.eq(Kaoqin::getType,"上班卡");

            //查询到当前人 打卡这一天是否有上班卡数据
            Kaoqin shangban = kaoqinService.getOne(kaoqinLambdaQueryWrapper);
            if (shangban!=null) {
                //数据库打卡时间，晚于当前打卡时间，保留当前打卡数据，删除数据库原有打卡数据
                if (shangban.getDakaTime().getTime()>kaoqin.getDakaTime().getTime()) {
                    //删除原有数据
                    kaoqinService.removeById(shangban.getId());
                    //添加新的打卡数据
                    kaoqinService.save(kaoqin);
                }
            }else{
                kaoqinService.save(kaoqin);
            }
        }else{
            LambdaQueryWrapper<Kaoqin> kaoqinLambdaQueryWrapper = new LambdaQueryWrapper<>();
            kaoqinLambdaQueryWrapper.eq(Kaoqin::getWorknum,kaoqin.getWorknum());
            kaoqinLambdaQueryWrapper.eq(Kaoqin::getWorkDate,kaoqin.getWorkDate());
            kaoqinLambdaQueryWrapper.eq(Kaoqin::getType,"下班卡");

            //查询到当前人 打卡这一天是否有下班卡数据
            Kaoqin xiaban = kaoqinService.getOne(kaoqinLambdaQueryWrapper);
            if (xiaban!=null) {
                //数据库打卡时间，早于当前打卡时间，保留当前打卡数据，删除数据库原有打卡数据
                if (xiaban.getDakaTime().getTime()<kaoqin.getDakaTime().getTime()) {
                    //删除原有数据
                    kaoqinService.removeById(xiaban.getId());
                    //添加新的打卡数据
                    kaoqinService.save(kaoqin);
                }
            }else{
                kaoqinService.save(kaoqin);
            }
        }
    }

}
